<template>
  <div class="components-container">
    <aside>
      <el-form label-position="center" :inline="true" label-width="80px" :model="listQuery" size="mini">
        <el-form-item label="ID">
          <el-input v-model="listQuery.id"></el-input>
        </el-form-item>
        <el-form-item label="名称">
          <el-input v-model="listQuery.fullName"></el-input>
        </el-form-item>
        <el-form-item label="颜色">
          <el-input v-model="listQuery.color"></el-input>
        </el-form-item>
        <el-form-item label="车牌号">
          <el-input v-model="listQuery.plateNumber"></el-input>
        </el-form-item>
        <el-form-item label="城市">
          <el-input v-model="listQuery.cityCode"></el-input>
        </el-form-item>

        <el-form-item label="运营状态">
          <el-select
            v-model="listQuery.operationStatus"
            placeholder="运营状态"
            clearable
            class="filter-item"
            style="width: 130px">
            <el-option
              v-for="item in optStatusQuery"
              :key="item.key"
              :label="item.display_name"
              :value="item.key"/>
          </el-select>
        </el-form-item>
        <el-form-item label="发布时间">
          <div class="block">
            <el-date-picker
              v-model="timeQuery"
              type="datetimerange"
              :picker-options="pickerOptions"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              align="right">
            </el-date-picker>
          </div>
        </el-form-item>
      </el-form>
    </aside>
    <div>
      <div class="filter-container" align="right">
        <el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">
          显示车辆外观
        </el-checkbox>
        <el-button
          class="filter-item"
          style="margin-left: 10px;"
          type="primary"
          icon="el-icon-edit"
          @click="handleCreate">
          添加
        </el-button>
        <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
          查找
        </el-button>
      </div>

      <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%;"
        @sort-change="sortChange"
      >
        <el-table-column
          label="车辆ID"
          prop="id"
          sortable="custom"
          align="center"
          width="100">
          <template slot-scope="{row}">
            <span>{{ row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column label="发布时间" width="180px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.publishTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="上牌时间" width="180px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.registDate }}</span>
          </template>
        </el-table-column>
        <el-table-column label="城市" width="50px">
          <template slot-scope="{row}">
            <span>{{ row.cityCode }}</span>
          </template>
        </el-table-column>
        <el-table-column label="车辆名称" width="110px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.fullName }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="showReviewer" label="车辆照片" width="110px" align="center">
          <template slot-scope="{row}">
            <el-image
              style="width: 100px; height: 100px"
              :src="row.carImg"
              fit="fit"></el-image>
          </template>
        </el-table-column>
        <el-table-column v-if="showReviewer" label="车辆颜色" width="110px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.color }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="showReviewer" label="车牌号" width="110px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.plateNumber }}</span>
          </template>
        </el-table-column>
        <el-table-column label="运营状态" class-name="status-col" width="100">
          <template slot-scope="{row}">
            <el-tag :type="row.operationStatus | statusFilter">
              {{ row.operationStatus | statusTextFilter }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <el-button type="primary" size="mini" @click="handleUpdate(row)">
              编辑
            </el-button>
<!--            <el-button type="primary" size="mini" @click="handleDetails(row)">-->
<!--              详情-->
<!--            </el-button>-->
            <el-button
              v-if="row.operationStatus !== 1"
              size="mini"
              type="success"
              @click="handleModifyStatus(row,1)">
              上架
            </el-button>
            <el-button
              type="warning"
              v-if="row.operationStatus !== 0 && row.operationStatus !== -1 "
              size="mini"
              @click="handleModifyStatus(row,0)">
              下架
            </el-button>
            <el-button v-if="row.operationStatus !== -1" size="mini" type="danger" @click="handleModifyStatus(row,-1)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        :v-show="true"
        :total="total"
        :page.sync="listQuery.pageNO"
        :limit.sync="listQuery.pageSize"
        @pagination="getList"/>

      <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
        <div v-if="dialogStatus !== 'details'">
          <el-form
            ref="dataForm"
            :rules="rules"
            :model="scopeData"
            label-position="left"
            label-width="70px"
            style="width: 400px; margin-left:50px;">
            <el-form-item label="车辆类型">
              <el-select v-model="scopeData.carTypeId" class="filter-item" placeholder="请选择车辆类型">
                <el-option
                  v-for="item in carTypeList"
                  :key="item.id"
                  :label="item.brand + ' ' + item.model"
                  :value="item.id"/>
              </el-select>
            </el-form-item>
            <el-form-item label="车辆等级">
              <el-select v-model="scopeData.carLevelId" class="filter-item" placeholder="请选择车辆等级">
                <el-option
                  v-for="item in carLevelList"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"/>
              </el-select>
            </el-form-item>
            <el-form-item label="发布时间">
              <el-date-picker
                v-model="scopeData.publishTime"
                type="date"
                value-format="yyyy-MM-dd HH:mm"
                placeholder="请选择日期"/>
            </el-form-item>
            <el-form-item label="上牌时间">
              <el-date-picker
                v-model="scopeData.registDate"
                type="date"
                value-format="yyyy-MM-dd HH:mm"
                placeholder="选择日期">
              </el-date-picker>
<!--              <el-date-picker-->
<!--                v-model=""-->
<!--                format="yyyy 年 MM 月 dd 日"-->
<!--                value-format="date"-->
<!--                type="date"-->
<!--                placeholder="请选择日期"-->
<!--              />-->
            </el-form-item>
            <el-form-item label="城市">
              <el-input v-model="scopeData.cityCode" placeholder="请输入城市"/>
            </el-form-item>
            <el-form-item label="车辆名称">
              <el-input v-model="scopeData.fullName" placeholder="请输入车辆名称"/>
            </el-form-item>
            <el-form-item label="车辆照片">
              <el-upload
                :headers="uploadHeader"
                class="avatar-uploader"
                action="http://localhost:8888/manager/index/upload"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :with-credentials="true">
                <img v-if="imageUrl" :src="imageUrl" class="avatar" width="300">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              <!--              <el-input v-model="scopeData.carImg" placeholder="请输入车辆名称"/>-->
            </el-form-item>
            <el-form-item label="车辆颜色">
              <el-input v-model="scopeData.color" placeholder="请输入车辆颜色"/>
            </el-form-item>
            <el-form-item label="车牌号">
              <el-input v-model="scopeData.plateNumber" placeholder="请输入车牌号"/>
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model="scopeData.remark" placeholder="请输入备注"/>
            </el-form-item>
          </el-form>
          <div slot="footer" align="right" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">
              取消
            </el-button>
            <el-button type="primary" @click="confirmD">
              确认
            </el-button>
          </div>
        </div>

      </el-dialog>

      <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
        <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
          <el-table-column prop="key" label="Channel"/>
          <el-table-column prop="pv" label="Pv"/>
        </el-table>
        <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  getCarLevelList,
  getCarList,
  publicCar,
  downCar,
  getCarTypeList,
  deleteCar,
  insertOrUpdateCar
} from '@/api/car'

import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination'
import { getToken } from '@/utils/auth'

const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]
const optStatusQuery = [
  { key: null, display_name: '全部' },
  { key: '-1', display_name: '已删除' },
  { key: '0', display_name: '未上架' },
  { key: '1', display_name: '已上架' },
  { key: '2', display_name: '待整备' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'CarList',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusTextFilter(status) {
      const statusMap = {
        '-1': '已删除',
        '0': '未上架',
        '1': '已上架',
        '2': '待整备'
      }
      return statusMap[status + '']
    },
    statusFilter(status) {
      const statusMap = {
        '-1': 'error',
        '0': 'info',
        '1': 'success',
        '2': 'warning'
      }
      return statusMap[status + '']
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      carTypeList: null,
      carLevelList: null,
      total: 0,
      listLoading: true,
      listQuery: {
        pageNO: 1,
        pageSize: 20,
        id: null,
        plateNumber: null,
        operationStatus: null,
        fullName: null,
        color: null,
        publishTimeStart: null,
        publishTimeEnd: null,
        cityCode: null
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      optStatusQuery,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      scopeData: {},
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增',
        details: '详情'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false,
      timeQuery: [],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      imageUrl: ''
    }
  },
  computed: {
    uploadHeader() {
      return {
        Authorization: 'Bearer ' + getToken()
      }
    }
  },
  created() {
    this.getList()
    this.getCarTypeList()
    this.getCarLevelList()
  },
  methods: {
    async getCarTypeList() {
      const res = await getCarTypeList(this.listQuery)
      this.carTypeList = res.data
    },
    async getCarLevelList() {
      const res = await getCarLevelList(this.listQuery)
      this.carLevelList = res.data
    },
    async getList() {
      this.listLoading = true
      this.listQuery.publishTimeStart = null
      this.listQuery.publishTimeEnd = null
      if (this.timeQuery && this.timeQuery.length > 1) {
        this.listQuery.publishTimeStart = this.timeQuery[0]
        this.listQuery.publishTimeEnd = this.timeQuery[1]
      }
      await getCarList(this.listQuery).then(response => {
        const { data } = response
        console.log(data)
        this.total = data.total
        this.list = data.records
        console.log(data.records.length)
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    statusTextFilter(status) {
      const statusMap = {
        '-1': '删除',
        '0': '下架',
        '1': '上架',
        '2': '待整备'
      }
      return statusMap[status + '']
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status, index) {
      const target = this.statusTextFilter(status)
      this.$confirm('确认对该车辆进行' + target + '吗？', 'Warning', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const param = {
            id: row.id
          }
          if (status === -1) {
            deleteCar(param)
          } else if (status === 0) {
            downCar(param)
          } else {
            publicCar(param)
          }
          this.$message({
            message: '操作Success',
            type: 'success'
          })
          row.operationStatus = status
        })
        .catch(err => {
          console.error(err)
        })
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    handleCreate() {
      this.imageUrl = ''
      this.scopeData = {}
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    handleUpdate(row) {
      console.log(row)
      this.imageUrl = row.carImg
      this.scopeData = row
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
    },
    handleDetails(row) {
      this.imageUrl = row.carImg
      this.scopeData = row
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'details'
      this.dialogFormVisible = true
    },
    handleDelete(row, index) {
      this.$notify({
        title: 'Success',
        message: 'Delete Successfully',
        type: 'success',
        duration: 2000
      })
      this.list.splice(index, 1)
    },
    handleAvatarSuccess(res, file) {
      console.log(res)
      this.scopeData.carImg = res.data
      console.log(this.scopeData)
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      return true
      // const isJPG = file.type === 'image/jpeg'
      // const isLt2M = file.size / 1024 / 1024 < 2
      //
      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!')
      // }
      // if (!isLt2M) {
      //   this.$message.error('上传头像图片大小不能超过 2MB!')
      // }
      // return isJPG && isLt2M
    },
    async confirmD() {
      const isEdit = this.dialogType === 'edit'
      console.log(isEdit)
      const data = this.scopeData
      const res = await insertOrUpdateCar(data)
      await this.getList()
      const { id } = res.data
      this.dialogFormVisible = false
      this.$notify({
        title: 'Success',
        dangerouslyUseHTMLString: true,
        message: `
            <div>车辆ID: ${id}</div>
          `,
        type: 'success'
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>
